﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;
using ContractManagementSystem.BusinessLogic;
using ContractManagementSystem.Common;

namespace ContractManagementSystem.Controls
{
    public partial class TimesheetUserControl : System.Web.UI.UserControl
    {
        const string AdminRole = "Admin";
        const string LineManagerRole = "LineManager";
        const string ContractorRole = "Contractor";
        const string ConsultantRole = "Consultant";
        const string DateTimeFormat = "MM/dd/yyyy";
        private const string TitleAddNewTimesheet = "Add new Timesheet";
        private const string TitleUpdateTimesheet = "Update Timesheet";
        private const string TitleRejectTimesheet = "Reject Timesheet";
        private const string TitleListTimesheet = "List Timesheet";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialPage();
            }
            ShowHidePanel();
            RejectButton.OnClientClick = "return validateTextBox(" + MessageTextBox.ClientID + ");";
        }

        private void BindList()
        {
            if (Session["Name"] != null)
            {
                string userName = Session["Name"].ToString();
                string role = UserBusiness.FetchRoleByUserName(userName);

                if (ContractDropDownList.SelectedIndex != 0 && ContractDropDownList.Items.Count > 0 &&
                    !string.IsNullOrEmpty(FromDateTextBox.Text) && !string.IsNullOrEmpty(ToDateTextBox.Text))
                {
                    DataTable source;
                    DateTime fromDate = Convert.ToDateTime(FromDateTextBox.Text, CultureInfo.CurrentCulture);
                    DateTime toDate = Convert.ToDateTime(ToDateTextBox.Text, CultureInfo.CurrentCulture);
                    string status = StatusDropDownList.SelectedItem.Value;
                    var contractId = new Guid(ContractDropDownList.SelectedItem.Value);

                    switch (role)
                    {
                        case AdminRole:
                            var contractorIdForAdmin = new Guid(UserBusiness.FetchContractorIdByUserName(ContractorTextBox.Text).Rows[0][0].ToString());
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForAdmin, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();

                            break;
                        case LineManagerRole:
                            Guid contractorIdForLineManager = new Guid(ContractorDropDownList.SelectedItem.Value);
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForLineManager, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();


                            if (source.Rows.Count > 0)
                            {
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var actionPanel = listViewDataItem.FindControl("ActionPanel") as Panel;
                                    actionPanel.Visible = false;
                                }
                            }

                            break;
                        case ContractorRole:
                            var contractorId = new Guid(UserBusiness.FetchIdByUserName(Session["Name"].ToString()));
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorId, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();

                            if (source.Rows.Count > 0)
                            {
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var statusPanel = listViewDataItem.FindControl("StatusPanel") as Panel;
                                    statusPanel.Visible = false;
                                }
                            }

                            break;
                        case ConsultantRole:
                            Guid contractorIdForConsultant = new Guid(ContractorDropDownList.SelectedItem.Value);
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForConsultant, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();

                            if (source.Rows.Count > 0)
                            {
                                var headerActionPanel = TimesheetListView.FindControl("HeaderActionPanel") as Panel;
                                headerActionPanel.Visible = false;
                                var headerConsultantPanel = TimesheetListView.FindControl("HeaderConsultantPanel") as Panel;
                                headerConsultantPanel.Visible = false;
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var statusPanel = listViewDataItem.FindControl("StatusPanel") as Panel;
                                    statusPanel.Visible = false;
                                    var actionPanel = listViewDataItem.FindControl("ActionPanel") as Panel;
                                    actionPanel.Visible = false;
                                    var consultantPanel = listViewDataItem.FindControl("ConsultantPanel") as Panel;
                                    consultantPanel.Visible = false;
                                }
                            }

                            break;
                    }
                    ContractDropDownList.DataBind();
                }
            }
        }

        private void BindContractor()
        {
            string userName = Session["Name"].ToString();
            Guid keyId = new Guid(UserBusiness.FetchProfileByUserName(userName).Rows[0][0].ToString());
            string role = UserBusiness.FetchRoleByUserName(userName);
            char key = role.Equals(LineManagerRole) ? 'L' : 'C';

            ContractorDropDownList.DataSource = ContractBusiness.FetchContractorByKey(keyId, key);
            ContractorDropDownList.DataValueField = "ContractorId";
            ContractorDropDownList.DataTextField = "FullName";
            ContractorDropDownList.DataBind();
            ContractorDropDownList.Items.Insert(0, "-- Choose item --");
        }

        private void InitialPage()
        {
            if (Session["Name"] != null)
            {
                string userName = Session["Name"].ToString();
                string role = UserBusiness.FetchRoleByUserName(userName);
                roleBox.Value = role;
                switch (role)
                {
                    case AdminRole:
                        AdminAction.Visible = true;
                        ContractorDropDownList.Visible = false;
                        break;
                    case ConsultantRole:
                        BindContractor();
                        ContractorDropDownList.Visible = true;
                        ContractorDropDownList.SelectedIndex = 0;
                        break;
                    case ContractorRole:
                        AdminAction.Visible = true;
                        ContractorSelectButton.Visible = false;
                        ContractorDropDownList.Visible = false;
                        ContractDropDownList.DataSource = ContractBusiness.FetchByContractorId(UserBusiness.FetchIdByUserName(Session["Name"].ToString()));
                        ContractDropDownList.DataValueField = "ContractId";
                        ContractDropDownList.DataTextField = "Name";
                        ContractDropDownList.DataBind();
                        ContractDropDownList.Items.Insert(0, "-- Choose item --");
                        ContractorTextBox.Enabled = false;
                        ContractorTextBox.Text = userName;
                        break;
                    case LineManagerRole:
                        BindContractor();
                        ContractorDropDownList.Visible = true;
                        break;
                }
            }
        }

        private void ShowHidePanel()
        {
            switch (roleBox.Value)
            {
                case ConsultantRole:
                    AddNewButton.Visible = false;
                    ActionTopPanel.Visible = false;
                    break;
                case ContractorRole:
                    BatchRejectTimesheet.Visible = false;
                    BatchApprovedButton.Visible = false;
                    break;
                case LineManagerRole:
                    AddNewButton.Visible = false;
                    BatchUpdateButton.Visible = false;
                    BatchDeleteButton.Visible = false;
                    break;
            }
        }

        protected void RejectLinkButton_OnCommand(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Split('$')[1], CultureInfo.CurrentCulture);
            DataTable source = new DataTable { Locale = CultureInfo.CurrentCulture };
            source.Columns.Add("TimesheetId", typeof(Guid));
            source.Columns.Add("WorkDate", typeof(DateTime));
            source.Columns.Add("WorkingTime", typeof(float));
            source.Columns.Add("Description", typeof(string));
            source.Columns.Add("Status", typeof(string));

            var timesheetId = new Guid(e.CommandArgument.ToString().Split('$')[0]);
            var workingTimeLabel = TimesheetListView.Items[id].FindControl("WorkingTimeLabel") as Label;
            var descriptionLabel = TimesheetListView.Items[id].FindControl("DescriptionLabel") as Label;
            var statusLabel = TimesheetListView.Items[id].FindControl("StatusLabel") as Label;
            var workDateLabel = TimesheetListView.Items[id].FindControl("WordDateLabel") as Label;
            if (!statusLabel.Text.Equals("Reject"))
            {
                source.Rows.Add(timesheetId, workDateLabel.Text, workingTimeLabel.Text, descriptionLabel.Text,
                            statusLabel.Text);
                RejectListView.DataSource = source;
                RejectListView.DataBind();

                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
                MessageTextBox.Text = "";
                TitleRejectTimesheetLabel.Text = TitleRejectTimesheet;
                StatusRejectTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Contract: " + ContractDropDownList.SelectedItem.Text +
                                                    "<span style='margin-left:40px;'>StartDate: " + FromDateTextBox.Text + "</span>" +
                                                    "<span style='margin-left:40px;'>EndDate: " + ToDateTextBox.Text + "</span>" +
                                                  "</div>";
                RejectPanel.Visible = true;
                searchPanel.Visible = false;
                MessageBottomPanel.Visible = true;
            }
        }

        protected void ApprovedLinkButton_OnCommand(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Split('$')[1], CultureInfo.CurrentCulture);
            var statusLabel = TimesheetListView.Items[id].FindControl("StatusLabel") as Label;
            if (!statusLabel.Text.Equals("Approved"))
            {
                var timesheetId = new Guid(e.CommandArgument.ToString().Split('$')[0]);
                int result = TimesheetBusiness.ApprovedTimesheet(timesheetId);
                if (result != 0)
                {
                    StatusListTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                        "Approved: " + result + " row(s)" +
                                                    "</div>";
                }
            }
        }

        protected void EditLinkButton_OnCommand(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Split('$')[1], CultureInfo.CurrentCulture);
            var statusLabel = TimesheetListView.Items[id].FindControl("StatusLabel") as Label;
            if (!statusLabel.Text.Equals("Approved"))
            {
                var timesheetId = new Guid(e.CommandArgument.ToString().Split('$')[0]);
                EditTimesheetListView.DataSource = TimesheetBusiness.FetchByTimesheetId(timesheetId);
                EditTimesheetListView.DataBind();
                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
                searchPanel.Visible = false;
                TitleUpdateTimesheetLabel.Text = TitleUpdateTimesheet;
                StatusUpdateTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Contract: " + ContractDropDownList.SelectedItem.Text +
                                                    "<span style='margin-left:40px;'>StartDate: " + FromDateTextBox.Text + "</span>" +
                                                    "<span style='margin-left:40px;'>EndDate: " + ToDateTextBox.Text + "</span>" +
                                                  "</div>";
                BottomPanel.Visible = true;
                ActionBottomPanel.Visible = true;

                var sourceDate = ContractBusiness.FetchContractDateById(new Guid(ContractDropDownList.SelectedValue));
                StartDateBox.Value = Convert.ToDateTime(sourceDate.Rows[0]["StartDate"], CultureInfo.CurrentCulture).ToShortDateString();
                EndDateBox.Value = Convert.ToDateTime(sourceDate.Rows[0]["EndDate"], CultureInfo.CurrentCulture).ToShortDateString();
            }
        }

        protected void DeleteLinkButton_OnCommand(object sender, CommandEventArgs e)
        {
            var timesheetId = new Guid(e.CommandArgument.ToString());
            int result = TimesheetBusiness.Inactive(timesheetId);
            if (result != 0)
            {
                StatusListTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Deleted: " + result + " row(s)" +
                                                "</div>";
            }
        }

        protected void TimesheetDataPager_OnPreRender(object sender, EventArgs e)
        {
            BindList();
        }

        protected void BatchApprovedButton_OnClick(object sender, EventArgs e)
        {
            var source = new DataTable{Locale = CultureInfo.CurrentCulture};
            source.Columns.Add("TimesheetId", typeof(Guid));
            foreach (ListViewDataItem item in TimesheetListView.Items)
            {
                var checkbox = item.FindControl("ItemCheckBox") as HtmlInputCheckBox;
                if (checkbox != null && checkbox.Checked)
                {
                    Guid newId = new Guid(checkbox.Value.Split('$')[0]);
                    source.Rows.Add(newId);
                }
            }
            if (source.Rows.Count > 0)
            {
                int result = TimesheetBusiness.BatchApproved(source);
                if (result != 0)
                {
                    StatusListTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                        "Approved: " + result + " row(s)" +
                                                    "</div>";
                }
            }
        }

        protected void UpdateButton_OnClick(object sender, EventArgs e)
        {
            var source = new DataTable{Locale = CultureInfo.CurrentCulture};
            source.Columns.Add("ContractId", typeof(Guid));
            source.Columns.Add("TimesheetId", typeof(Guid));
            source.Columns.Add("Description", typeof(string));
            source.Columns.Add("WorkingTime", typeof(float));
            source.Columns.Add("WorkDate", typeof(DateTime));
            foreach (ListViewDataItem listViewDataItem in EditTimesheetListView.Items)
            {
                var label = listViewDataItem.FindControl("TimesheetId") as Label;
                var workDateTextBox = listViewDataItem.FindControl("WorkDateTextBox") as TextBox;
                var timeTextBox = listViewDataItem.FindControl("TimeTextBox") as TextBox;
                var descriptionTextBox = listViewDataItem.FindControl("DescriptionTextBox") as TextBox;

                if (ValidateHelper.IsValidDateTime(workDateTextBox.Text, DateTimeFormat) &&
                            !ValidateHelper.IsValidDescript(descriptionTextBox.Text) &&
                            ValidateHelper.IsValidFloat(timeTextBox.Text))
                {
                    var contractId = new Guid(ContractDropDownList.SelectedValue);
                    var timesheetId = new Guid(label.Text);
                    var workDate = Convert.ToDateTime(workDateTextBox.Text, CultureInfo.CurrentCulture);
                    var time = float.Parse(timeTextBox.Text, CultureInfo.CurrentCulture);
                    var description = descriptionTextBox.Text;
                    source.Rows.Add(contractId, timesheetId, description, time, workDate);
                }
            }
            int result = TimesheetBusiness.BatchUpdate(source);
            if (result > 0)
            {
                TopPanel.Visible = true;
                TitleListTimesheetLabel.Text = TitleListTimesheet;
                StatusListTimesheetLabel.Text = "<div class='statusLabel'>Updated: " + result + " row(s).</div>";
                ActionTopPanel.Visible = true;
                BottomPanel.Visible = false;
                ActionBottomPanel.Visible = false;
                searchPanel.Visible = true;
            }

        }

        protected void BackButton_OnClick(object sender, EventArgs e)
        {
            TopPanel.Visible = true;
            searchPanel.Visible = true;
            ActionTopPanel.Visible = true;
            BottomPanel.Visible = false;
            MessageBottomPanel.Visible = false;
            MessageTextBox.Text = null;
            ActionBottomPanel.Visible = false;
            RejectPanel.Visible = false;
            AddNewPanel.Visible = false;
            ActionAddNewPanel.Visible = false;
            TitleListTimesheetLabel.Text = TitleListTimesheet;
            StatusListTimesheetLabel.Text = "";
        }

        protected void BatchUpdateButton_OnClick(object sender, EventArgs e)
        {
            var source = new DataTable { Locale = CultureInfo.CurrentCulture };
            source.Columns.Add("TimesheetId", typeof(Guid));
            source.Columns.Add("Description", typeof(string));
            source.Columns.Add("WorkingTime", typeof(float));
            source.Columns.Add("WorkDate", typeof(DateTime));
            source.Columns.Add("Status", typeof(string));
            foreach (ListViewDataItem listViewDataItem in TimesheetListView.Items)
            {
                var itemCheckBox = listViewDataItem.FindControl("ItemCheckBox") as HtmlInputCheckBox;

                if (itemCheckBox != null && itemCheckBox.Checked)
                {
                    var wordDateLabel = listViewDataItem.FindControl("WordDateLabel") as Label;
                    var workingTimeLabel = listViewDataItem.FindControl("WorkingTimeLabel") as Label;
                    var descriptionLabel = listViewDataItem.FindControl("DescriptionLabel") as Label;
                    var statusLabel = listViewDataItem.FindControl("StatusLabel") as Label;

                    var timesheetId = new Guid(itemCheckBox.Value.Split('$')[0]);
                    var workDate = Convert.ToDateTime(wordDateLabel.Text, CultureInfo.CurrentCulture);
                    var time = float.Parse(workingTimeLabel.Text, CultureInfo.CurrentCulture);
                    var description = descriptionLabel.Text;
                    var status = statusLabel.Text;
                    source.Rows.Add(timesheetId, description, time, workDate, status);
                }
            }
            if (source.Rows.Count > 0)
            {
                EditTimesheetListView.DataSource = source;
                EditTimesheetListView.DataBind();
                TopPanel.Visible = false;
                searchPanel.Visible = false;
                ActionTopPanel.Visible = false;
                BottomPanel.Visible = true;
                ActionBottomPanel.Visible = true;
                TitleUpdateTimesheetLabel.Text = TitleUpdateTimesheet;
                StatusUpdateTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Contract: " + ContractDropDownList.SelectedItem.Text +
                                                    "<span style='margin-left:40px;'>StartDate: " + FromDateTextBox.Text + "</span>" +
                                                    "<span style='margin-left:40px;'>EndDate: " + ToDateTextBox.Text + "</span>" +
                                                  "</div>";
                var sourceDate = ContractBusiness.FetchContractDateById(new Guid(ContractDropDownList.SelectedValue));
                StartDateBox.Value = Convert.ToDateTime(sourceDate.Rows[0]["StartDate"],CultureInfo.CurrentCulture).ToShortDateString();
                EndDateBox.Value = Convert.ToDateTime(sourceDate.Rows[0]["EndDate"], CultureInfo.CurrentCulture).ToShortDateString();
            }
        }

        protected void RejectButton_OnClick(object sender, EventArgs e)
        {
            DataTable source = new DataTable { Locale = CultureInfo.CurrentCulture };
            source.Columns.Add("TimesheetId", typeof(Guid));
            source.Columns.Add("Reason", typeof(string));
            string reason = MessageTextBox.Text;
            if (!string.IsNullOrEmpty(reason))
            {
                foreach (ListViewDataItem listViewDataItem in RejectListView.Items)
                {
                    var timesheetIdLabel = listViewDataItem.FindControl("TimesheetIdLabel") as Label;
                    var timesheetId = new Guid(timesheetIdLabel.Text);
                    source.Rows.Add(timesheetId, reason);
                }

                int result = TimesheetBusiness.BatchReject(source);
                if (result > 0)
                {
                    TopPanel.Visible = true;
                    ActionTopPanel.Visible = true;
                    BottomPanel.Visible = false;
                    RejectPanel.Visible = false;
                    searchPanel.Visible = true;
                    TitleListTimesheetLabel.Text = TitleListTimesheet;
                    StatusListTimesheetLabel.Text = "<div class='statusLabel'>Rejected: " + result + " row(s).</div>";
                    MessageBottomPanel.Visible = false;
                }
            }
        }

        protected void BatchRejectTimesheet_OnClick(object sender, EventArgs e)
        {
            var source = new DataTable{Locale = CultureInfo.CurrentCulture};
            source.Columns.Add("TimesheetId", typeof(Guid));
            source.Columns.Add("Description", typeof(string));
            source.Columns.Add("WorkingTime", typeof(float));
            source.Columns.Add("WorkDate", typeof(DateTime));
            source.Columns.Add("Status", typeof(string));
            foreach (ListViewDataItem listViewDataItem in TimesheetListView.Items)
            {
                var itemCheckBox = listViewDataItem.FindControl("ItemCheckBox") as HtmlInputCheckBox;

                if (itemCheckBox != null && itemCheckBox.Checked)
                {
                    var wordDateLabel = listViewDataItem.FindControl("WordDateLabel") as Label;
                    var workingTimeLabel = listViewDataItem.FindControl("WorkingTimeLabel") as Label;
                    var descriptionLabel = listViewDataItem.FindControl("DescriptionLabel") as Label;
                    var statusLabel = listViewDataItem.FindControl("StatusLabel") as Label;

                    if (!statusLabel.Text.Equals("Reject"))
                    {
                        var timesheetId = new Guid(itemCheckBox.Value.Split('$')[0]);
                        var workDate = Convert.ToDateTime(wordDateLabel.Text, CultureInfo.CurrentCulture);
                        var time = float.Parse(workingTimeLabel.Text, CultureInfo.CurrentCulture);
                        var description = descriptionLabel.Text;
                        var status = statusLabel.Text;
                        source.Rows.Add(timesheetId, description, time, workDate, status);
                    }
                }
            }
            if (source.Rows.Count > 0)
            {
                RejectListView.DataSource = source;
                RejectListView.DataBind();
                TopPanel.Visible = false;
                TitleRejectTimesheetLabel.Text = TitleListTimesheet;
                StatusRejectTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Contract: " + ContractDropDownList.SelectedItem.Text +
                                                    "<span style='margin-left:40px;'>StartDate: " + FromDateTextBox.Text + "</span>" +
                                                    "<span style='margin-left:40px;'>EndDate: " + ToDateTextBox.Text + "</span>" +
                                                  "</div>";
                ActionTopPanel.Visible = false;
                RejectPanel.Visible = true;
                MessageTextBox.Text = "";
                MessageBottomPanel.Visible = true;
                searchPanel.Visible = false;
            }
        }

        protected void AddNewButton_OnClick(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0 && ContractDropDownList.Items.Count > 0)
            {
                var contractId = new Guid(ContractDropDownList.SelectedValue);
                AddNewListView.DataSource = TimesheetBusiness.CreateNew(contractId, DateTime.Now);
                AddNewListView.DataBind();
                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
                TitleAddNewTimesheetLabel.Text = TitleAddNewTimesheet;
                var sourceDate = ContractBusiness.FetchContractDateById(new Guid(ContractDropDownList.SelectedValue));
                var endDate = Convert.ToDateTime(sourceDate.Rows[0]["EndDate"],CultureInfo.CurrentCulture).ToShortDateString();
                var startDate = Convert.ToDateTime(sourceDate.Rows[0]["StartDate"],CultureInfo.CurrentCulture).ToShortDateString();
                StatusAddNewTimesheetLabel.Text = "<div class='statusLabel'>" +
                                                    "Contract: " + ContractDropDownList.SelectedItem.Text +
                                                    "<span style='margin-left:40px;'>StartDate: " + startDate + "</span>" +
                                                    "<span style='margin-left:40px;'>EndDate: " + endDate + "</span>" + 
                                                  "</div>";
                AddNewPanel.Visible = true;
                searchPanel.Visible = false;
                ActionAddNewPanel.Visible = true;
                StartDateBox.Value = startDate;
                EndDateBox.Value = endDate;
            }
        }

        protected void AddNewTimesheetButton_OnClick(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0)
            {
                var source = new DataTable { Locale = CultureInfo.CurrentCulture };
                source.Columns.Add("ContractId", typeof(Guid));
                source.Columns.Add("WorkDate", typeof(DateTime));
                source.Columns.Add("WorkingTime", typeof(float));
                source.Columns.Add("Description", typeof(string));

                string indexString = hiddenBox.Value;
                if (string.IsNullOrEmpty(indexString) || indexString.Equals("start"))
                {
                    foreach (var listViewDataItem in AddNewListView.Items)
                    {
                        var workDateTexBox = listViewDataItem.FindControl("WorkDateTextBox") as TextBox;
                        var workingTimeTexBox = listViewDataItem.FindControl("TimeTextBox") as TextBox;
                        var descriptionTexBox = listViewDataItem.FindControl("DescriptionTextBox") as TextBox;

                        if (ValidateHelper.IsValidDateTime(workDateTexBox.Text, DateTimeFormat) &&
                            !ValidateHelper.IsValidDescript(descriptionTexBox.Text) &&
                            ValidateHelper.IsValidFloat(workingTimeTexBox.Text))
                        {
                            var contractId = new Guid(ContractDropDownList.SelectedValue);
                            var workDate = Convert.ToDateTime(workDateTexBox.Text, CultureInfo.CurrentCulture);
                            var workingTime = float.Parse(workingTimeTexBox.Text, CultureInfo.CurrentCulture);
                            var desciption = descriptionTexBox.Text;

                            source.Rows.Add(contractId, workDate, workingTime, desciption);
                        }
                    }
                }
                else
                {
                    for (int i = 1; i < indexString.Split('$').Length; i++)
                    {
                        var index = Convert.ToInt32(indexString.Split('$')[i], CultureInfo.CurrentCulture);
                        var workDateTexBox = AddNewListView.Items[index].FindControl("WorkDateTextBox") as TextBox;
                        var workingTimeTexBox = AddNewListView.Items[index].FindControl("TimeTextBox") as TextBox;
                        var descriptionTexBox = AddNewListView.Items[index].FindControl("DescriptionTextBox") as TextBox;

                        if (ValidateHelper.IsValidDateTime(workDateTexBox.Text, DateTimeFormat) &&
                            !ValidateHelper.IsValidDescript(descriptionTexBox.Text) &&
                            ValidateHelper.IsValidFloat(workingTimeTexBox.Text))
                        {
                            var contractId = new Guid(ContractDropDownList.SelectedValue);
                            var workDate = Convert.ToDateTime(workDateTexBox.Text, CultureInfo.CurrentCulture);
                            var workingTime = float.Parse(workingTimeTexBox.Text, CultureInfo.CurrentCulture);
                            var desciption = descriptionTexBox.Text;

                            source.Rows.Add(contractId, workDate, workingTime, desciption);
                        }
                    }
                }

                int result = TimesheetBusiness.BatchInsert(source);

                if (result > 0)
                {
                    TopPanel.Visible = true;
                    ActionTopPanel.Visible = true;
                    AddNewPanel.Visible = false;
                    ActionAddNewPanel.Visible = false;
                    TitleListTimesheetLabel.Text = TitleListTimesheet;
                    StatusListTimesheetLabel.Text = "<div class='statusLabel'>Added: " + result + " row(s).</div>";
                    searchPanel.Visible = true;
                }
            }
        }

        protected void BatchDeleteButton_OnClick(object sender, EventArgs e)
        {
            var source = new DataTable { Locale = CultureInfo.CurrentCulture };
            source.Columns.Add("TimesheetId", typeof(Guid));
            foreach (ListViewDataItem item in TimesheetListView.Items)
            {
                var checkbox = item.FindControl("ItemCheckBox") as HtmlInputCheckBox;
                if (checkbox != null && checkbox.Checked)
                {
                    Guid newId = new Guid(checkbox.Value.Split('$')[0]);
                    source.Rows.Add(newId);
                }
            }
            if (source.Rows.Count > 0)
            {
                int result = TimesheetBusiness.BatchInactive(source);
                if (result != 0)
                {
                    StatusListTimesheetLabel.Text = "<div class='statusLabel'>Deleted: " + result + " row(s).</div>";
                }
            }
        }

        protected void ContractorSelectButton_OnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ContractorTextBox.Text))
            {
                DataTable contractorIdSource = UserBusiness.FetchContractorIdByUserName(ContractorTextBox.Text);
                if (!string.IsNullOrEmpty(UserBusiness.ErrorMessage) || contractorIdSource.Rows.Count != 0)
                {
                    string contractorId = contractorIdSource.Rows[0][0].ToString();
                    CheckContractorLiteral.Visible = false;
                    ContractDropDownList.DataSource = ContractBusiness.FetchByContractorId(contractorId);
                    ContractDropDownList.DataValueField = "ContractId";
                    ContractDropDownList.DataTextField = "Name";
                    ContractDropDownList.DataBind();
                    ContractDropDownList.Items.Insert(0, "-- Choose item --");
                }
                else
                {
                    CheckContractorLiteral.Visible = true;
                    ContractDropDownList.Items.Clear();
                    TopPanel.Visible = false;
                    ActionTopPanel.Visible = false;
                }
            }
            else
            {
                CheckContractorLiteral.Visible = true;
                ContractDropDownList.Items.Clear();
                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
            }
        }

        protected void ContractorDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ContractorDropDownList.SelectedIndex != 0)
            {
                var contractorId = new Guid(ContractorDropDownList.SelectedItem.Value);

                string userName = Session["Name"].ToString();
                Guid keyId = new Guid(UserBusiness.FetchProfileByUserName(userName).Rows[0][0].ToString());
                string role = UserBusiness.FetchRoleByUserName(userName);
                char key = role.Equals(LineManagerRole) ? 'L' : 'C';

                ContractDropDownList.DataSource = ContractBusiness.FetchContractByKey(contractorId, keyId, key);
                ContractDropDownList.DataValueField = "ContractId";
                ContractDropDownList.DataTextField = "Name";
                ContractDropDownList.DataBind();
                ContractDropDownList.Items.Insert(0, "-- Choose item --");
            }
            else
            {
                ContractDropDownList.Items.Clear();
            }
        }

        protected void ContractDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0)
            {
                var contractId = new Guid(ContractDropDownList.SelectedItem.Value);

                DataTable source = ContractBusiness.FetchContractDateById(contractId);

                FromDateTextBox.Text = Convert.ToDateTime(source.Rows[0]["StartDate"], CultureInfo.CurrentCulture).ToShortDateString();
                ToDateTextBox.Text = Convert.ToDateTime(source.Rows[0]["EndDate"], CultureInfo.CurrentCulture).ToShortDateString();
            }
            else
            {
                FromDateTextBox.Text = "";
                ToDateTextBox.Text = "";
                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
            }
        }

        protected void ListTimesheetButton_OnClick(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0 && ContractorDropDownList.SelectedIndex != 0 &&
                !string.IsNullOrEmpty(FromDateTextBox.Text) && !string.IsNullOrEmpty(ToDateTextBox.Text))
            {
                BindList();
                TopPanel.Visible = true;
                ActionTopPanel.Visible = true;
                TitleListTimesheetLabel.Text = TitleListTimesheet;
                ShowHidePanel();
            }
            else
            {
                TopPanel.Visible = false;
                ActionTopPanel.Visible = false;
            }
        }

        protected void TimesheetListView_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Label rejectStatus;
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                rejectStatus = e.Item.FindControl("StatusLabel") as Label;
                if (rejectStatus.Text.Equals("Reject"))
                {
                    rejectStatus.CssClass = "forReject";

                    var itemCheckBox = e.Item.FindControl("ItemCheckBox") as HtmlInputCheckBox;
                    Guid timesheetId = new Guid(itemCheckBox.Value.Split('$')[0]);

                    string reasonMessage = TimesheetBusiness.FetchReasonByTimesheetId(timesheetId).Rows[0]["Reason"].ToString();

                    rejectStatus.ToolTip = reasonMessage;
                }
            }
        }
    }
}